#include "gameroom.h"
#include <QPainter>
#include <QPixmap>
#include <QIcon>
#include <QPushButton>
#include <QFont>
#include <QSound>
#include <QTimer>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include "gameselect.h"

GameRoom::GameRoom(QWidget *parent) : QWidget(parent)
{
    //设置窗口大小
    this->setFixedSize(1000,800);

    //设置窗口图标
    this->setWindowIcon(QIcon(":res/ico.png"));

    //设置窗口标题
    this->setWindowTitle("游戏房间");

    //初始化贪吃蛇
    snakeList.push_back(QRectF(this->width()*0.5,this->height()*0.5,KSnakeNodeWidth,KSnakeNodeHeight));

    moveUp();
    moveUp();

    //创造食物
    createNewFood();

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,[=](){
        int cnt = 1;

        //intersects是判断两个矩形会不会相交
        if(snakeList.front().intersects(foodRect))
        {
            createNewFood();
            cnt++;
            QSound::play(":res/eatfood.wav");
        }

        while(cnt--)
        {
            switch (moveDirect) {
                case SnakeDirect::UP:
                    moveUp();
                    break;
                case SnakeDirect::DOWN:
                    moveDown();
                    break;
                case SnakeDirect::LEFT:
                    moveLeft();
                    break;
                case SnakeDirect::RIGHT:
                    moveRight();
                    break;
            }
        }

        //删除最后一个节点
        snakeList.pop_back();
        update();
    });


    //开始和暂停游戏按钮
    QPushButton* startBtn = new QPushButton(this);
    QPushButton* stopBtn = new QPushButton(this);

    startBtn->move(860,150);
    stopBtn->move(860,200);

    startBtn->setText("开始");
    stopBtn->setText("暂停");

    QFont font("楷体",20);
    startBtn->setFont(font);
    stopBtn->setFont(font);

    connect(startBtn,&QPushButton::clicked,[=](){
        isGameStart = true;
        timer->start(moveTimeout);
        sound = new QSound(":res/Trepak.wav");
//        if((sound->isFinished()) == false)
//        {
        sound->play();
//        }

        sound->setLoops(-1);//循环播放
    });

    connect(stopBtn,&QPushButton::clicked,[=](){
        isGameStart = false;
        timer->stop();
        sound->stop();
    });

    //方向控制
    QPushButton* up = new QPushButton(this);
    QPushButton* down = new QPushButton(this);
    QPushButton* left = new QPushButton(this);
    QPushButton* right = new QPushButton(this);

    up->move(880,400);
    down->move(880,480);
    left->move(840,440);
    right->move(920,440);

    up->setText("↑");
    down->setText("↓");
    left->setText("←");
    right->setText("→");

    up->setStyleSheet("QPushButton{border:0px;}");
    down->setStyleSheet("QPushButton{border:0px;}");
    left->setStyleSheet("QPushButton{border:0px;}");
    right->setStyleSheet("QPushButton{border:0px;}");

    QFont ft("宋体",28);
    up->setFont(ft);
    left->setFont(ft);
    right->setFont(ft);
    down->setFont(ft);

    connect(up,&QPushButton::clicked,[=](){
       if(moveDirect != SnakeDirect::DOWN)
       {
           moveDirect = SnakeDirect::UP;
       }
    });

    connect(down,&QPushButton::clicked,[=](){
       if(moveDirect != SnakeDirect::UP)
       {
           moveDirect = SnakeDirect::DOWN;
       }
    });

    connect(left,&QPushButton::clicked,[=](){
       if(moveDirect != SnakeDirect::RIGHT)
       {
           moveDirect = SnakeDirect::LEFT;
       }
    });

    connect(right,&QPushButton::clicked,[=](){
       if(moveDirect != SnakeDirect::LEFT)
       {
           moveDirect = SnakeDirect::RIGHT;
       }
    });

    //退出游戏按钮
    QPushButton* ExitBtn = new QPushButton(this);
    ExitBtn->move(860,760);
    ExitBtn->setText("退出");
    ExitBtn->setFont(font);

    QMessageBox* msg = new QMessageBox(this);
    msg->setWindowTitle("退出游戏");
    msg->setText("是否退出游戏?");
    QPushButton* ok = new QPushButton("ok");
    QPushButton* cancel = new QPushButton("cancel");

    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(cancel,QMessageBox::RejectRole);

    connect(ExitBtn,&QPushButton::clicked,[=](){
       msg->show();
       msg->exec();
       QSound::play(":res/clicked.wav");

       GameSelect* select = new GameSelect;

       if(msg->clickedButton() == ok)
       {
           this->close();
           sound->stop();
           select->show();
       }
       else
       {
           msg->close();
       }
    });
}

void GameRoom::paintEvent(QPaintEvent *event)
{
    //实例化画家对象
    QPainter painter(this);

    //实例化绘图设备
    QPixmap pix;
    pix.load(":res/game_room.png");

    //绘画贪吃蛇游戏背景
    painter.drawPixmap(0,0,800,800,pix);

    //绘画贪吃蛇控制界面背景
    pix.load(":res/bg1.png");
    painter.drawPixmap(800,0,200,900,pix);


    //绘制蛇 蛇头+蛇身+蛇尾
    //绘制蛇头 上 下 左 右
    if(moveDirect == SnakeDirect::UP)
    {
        pix.load(":res/up.png");
    }else if(moveDirect == SnakeDirect::DOWN)
    {
        pix.load(":res/down.png");
    }else if(moveDirect == SnakeDirect::LEFT)
    {
        pix.load(":res/left.png");
    }else
    {
        pix.load(":res/right.png");
    }

    auto snakeHead = snakeList.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),pix);

    //绘制蛇身
    pix.load(":res/Bd.png");
    for (int i = 1; i < snakeList.size() - 1; i++)
    {
        auto node = snakeList.at(i);
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),pix);
    }

    //绘制蛇尾
    auto snakeTail = snakeList.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),pix);

    //绘制食物
    pix.load(":res/food.bmp");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pix);

    //绘制分数
    pix.load(":res/sorce_bg.png");
    painter.drawPixmap(this->width()*0.85,this->height()*0.06,90,40,pix);

    QPen pen;
    pen.setColor(Qt::black);
    painter.setPen(pen);
    QFont font("方正舒体",22);
    painter.setFont(font);
    painter.drawText(this->width()*0.9,this->height()*0.1,QString("%1").arg(snakeList.size()));

    //往文件写分数
    int len = snakeList.size();
    QFile file("E:/bit/qtcode/greedy_snake/snake/res/1.txt");
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(&file);
        int num = len;
        out << num;
        file.close();
    }

    //绘制游戏失败效果
    if(checkFail())
    {
        pen.setColor(Qt::red);
        painter.setPen(pen);
        QFont font("方正舒体",50);
        painter.setFont(font);
        painter.drawText(this->width()*0.45,this->height()*0.5,QString("GAME OVER!"));
        timer->stop();
        QSound::play(":res/gaveover.wav");

        sound->stop();
    }
}

void GameRoom::moveUp()
{
    //蛇的左上角坐标
    QPointF leftTop;
    //蛇的右下角坐标
    QPointF rightBottom;
    //蛇头
    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    //穿墙了
    if(headY < 0)
    {
        leftTop = QPointF(headX,this->height()-KSnakeNodeHeight);
    }
    else
    {
        leftTop = QPointF(headX,headY-KSnakeNodeHeight);
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}


void GameRoom::moveDown()
{
    //蛇的左上角坐标
    QPointF leftTop;
    //蛇的右下角坐标
    QPointF rightBottom;
    //蛇头
    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    //穿墙了
    if(headY > this->height())
    {
        leftTop = QPointF(headX,0);
    }
    else
    {
        leftTop = snakeNode.bottomLeft();
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveLeft()
{
    //蛇的左上角坐标
    QPointF leftTop;
    //蛇的右下角坐标
    QPointF rightBottom;
    //蛇头
    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    //穿墙了
    if(headX < 0)
    {
        leftTop = QPointF(800-KSnakeNodeWidth,headY);
    }
    else
    {
        leftTop = QPointF(headX-KSnakeNodeWidth,headY);
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveRight()
{
    //蛇的左上角坐标
    QPointF leftTop;
    //蛇的右下角坐标
    QPointF rightBottom;
    //蛇头
    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    //穿墙了
    if(headX + KSnakeNodeWidth > 780)
    {
        leftTop = QPointF(0,headY);
    }
    else
    {
        leftTop = snakeNode.topRight();
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

bool GameRoom::checkFail()
{
    for(int i = 0; i < snakeList.size(); i++)
    {
        for(int j = i + 1; j < snakeList.size(); j++)
        {
            if(snakeList.at(i) == snakeList.at(j))
            {
                return true;
            }
        }
    }

    return false;
}

void GameRoom::createNewFood()
{
    foodRect = QRectF(qrand() % (800 / KSnakeNodeWidth) * KSnakeNodeWidth,
                      qrand() % (this->height() / KSnakeNodeHeight) * KSnakeNodeHeight,
            KSnakeNodeWidth,KSnakeNodeHeight);
}

